package by.gravity.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;

public class FileUtil {

	private static final String TAG = FileUtil.class.getSimpleName();

	private static final String UTF8 = "UTF8";

	private static final int BUFFER_SIZE = 8192;

	private static final String FILE = "file://";

	public static void writeToFile(String path, String fileName, String str) {

		if (str == null) {
			Log.e(TAG, "won't write null string to file");
			return;
		}

		File file = new File(path, fileName);
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file, true);
			fileWriter.write(str);
			fileWriter.write("\n");
			fileWriter.flush();
			Log.i(TAG, "written to file: " + file.getName());
		} catch (IOException e) {
			Log.e(TAG, "error writing xml to file", e);
		} finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static String readFileAsString(String filePath) {
		try {
			if (filePath == null) {
				return null;
			}
			filePath = removeFileFromStartPath(filePath);
			StringBuffer fileData = new StringBuffer(1000);
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), UTF8), BUFFER_SIZE);
			char[] buf = new char[1024];
			int numRead = 0;
			while ((numRead = reader.read(buf)) != -1) {
				String readData = String.valueOf(buf, 0, numRead);
				fileData.append(readData);
				buf = new char[1024];
			}
			reader.close();
			return fileData.toString();
		} catch (java.io.IOException e) {
			e.printStackTrace();
		}

		return null;

	}

	public static String removeFileFromStartPath(String filePath) {
		if (filePath.startsWith(FILE)) {
			return filePath.split(FILE)[1];
		}

		return filePath;
	}

	public static String getFileNameFromPath(String filePath) {
		File file = new File(filePath);
		String name = file.getName();
		return name;
	}

	public static String getFilePathFromContentUri(Uri selectedVideoUri) {
		ContentResolver contentResolver = ContextHolder.getContext().getContentResolver();
		String filePath;
		String[] filePathColumn = { MediaColumns.DATA };

		Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
		if (cursor != null && cursor.moveToFirst()) {
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			filePath = cursor.getString(columnIndex);
			cursor.close();
			return FILE + filePath;
		}
		return selectedVideoUri.toString();
	}

	public static String getDefaultMediaPath() {
		if (Environment.getExternalStorageState() == null) {
			return null;
		}

		return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
	}

	public static String readAssets(String fileName, Context context) {
		StringBuilder returnString = new StringBuilder();
		InputStream fIn = null;
		InputStreamReader isr = null;
		BufferedReader input = null;
		try {
			fIn = context.getResources().getAssets().open(fileName);
			isr = new InputStreamReader(fIn, "UTF-8");
			input = new BufferedReader(isr);
			String line = "";
			while ((line = input.readLine()) != null) {
				returnString.append(line);
			}
		} catch (Exception e) {
			e.getMessage();
		} finally {
			try {
				if (isr != null)
					isr.close();
				if (fIn != null)
					fIn.close();
				if (input != null)
					input.close();
			} catch (Exception e2) {
				e2.getMessage();
			}
		}
		return returnString.toString();
	}

	public static String getFileNameWithoutExtension(File file) {
		if (file == null) {
			return "";
		}
		String name = file.getName();
		int pos = name.lastIndexOf(".");
		if (pos > 0) {
			name = name.substring(0, pos);
		}

		return name;
	}
}